package com.my.lucky.service;

import com.my.lucky.model.FilterCondition;
import com.my.lucky.repository.FilterConditionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class FilterConditionService {

    @Autowired
    private FilterConditionRepository filterConditionRepository;

    // 获取当前用户的所有过滤条件
    public List<FilterCondition> getFilterConditionsByUser(Long userId) {
        return filterConditionRepository.findByUserIdOrderByCreatedAtDesc(userId);
    }

    // 保存或更新过滤条件
    @Transactional
    public FilterCondition saveFilterCondition(FilterCondition condition) {
        // 检查同名条件，如果存在则更新
        FilterCondition existing = filterConditionRepository.findByUserIdAndName(
                condition.getUserId(), condition.getName());

        if (existing != null) {
            condition.setId(existing.getId());
        }

        return filterConditionRepository.save(condition);
    }

    // 根据ID和用户ID获取过滤条件
    public FilterCondition getFilterConditionByIdAndUser(Long id, Long userId) {
        return filterConditionRepository.findById(id)
                .filter(condition -> condition.getUserId().equals(userId))
                .orElse(null);
    }

    // 删除过滤条件
    @Transactional
    public void deleteFilterCondition(Long id, Long userId) {
        filterConditionRepository.findById(id)
                .filter(condition -> condition.getUserId().equals(userId))
                .ifPresent(filterConditionRepository::delete);
    }
}
